package com.xjoyt.pay.master.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;

import com.xjoyt.pay.abstracts.AbstractDao;
import com.xjoyt.pay.dto.PageParam;
import com.xjoyt.pay.dto.PageResult;
import com.xjoyt.pay.master.dao.CashDetailRepositoryCustom;
import com.xjoyt.pay.master.dao.predicate.CashDetailCommands;
import com.xjoyt.pay.master.params.CashDetailPageParam;
import com.xjoyt.pay.master.po.CashDetail;
import com.xjoyt.pay.master.repository.CashDetailRepository;

public class CashDetailRepositoryImpl extends AbstractDao implements CashDetailRepositoryCustom {

	@Autowired
	private CashDetailRepository cashDetailRepository;

	@Override
	public PageResult<CashDetail> loadPageMap(PageParam<CashDetailPageParam> param) {
		Pageable pageable = getPageable(param);
		Specification<CashDetail> spec = getSpecification(CashDetailCommands.class, param.query);
		Page<CashDetail> pageResult = cashDetailRepository.findAll(spec, pageable);
		return new PageResult<>(pageResult.getTotalElements(), pageResult.getContent());
	}
	
	@Override
	public List<Map<String, Object>> sum(List<String> cashIds){
		
		StringBuilder builder = new StringBuilder(
				" select new map(a.cash.id as id, sum(a.money) as moneySum, sum(a.cashMoney) as cashMoney, sum( a.money * a.rate + a.poundage + a.limit + a.minimum ) as poundageSum) from CashDetail a where a.cash.id in :ids ");
		Map<String, Object> params = new HashMap<>();
		params.put("ids", cashIds);
		
		builder.append(" group by a.cash.id ");
		Query query = entityManager.createQuery(builder.toString());
		for (Entry<String, Object> entry : params.entrySet()) {
			query.setParameter(entry.getKey(), entry.getValue());
		}

		@SuppressWarnings("unchecked")
		List<Map<String, Object>> result = query.getResultList();
		return result;
	}

}
